const app = getApp();
const updateValue = require('./../../../utils/updateValue');
const qiniu = require('./../../../utils/qiniuSdk')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        cid: '',
        dietType: -1,
        info: {},
        dietRx: {},
        actionRxInfos: [],
        imageList: [],
        val: {
            start: 0,
            size: 10,
            diagnosisId: ''
        },
        list: [],
        num: 0,
        typeListOpt: [],
        typeList: [],
		typeImgList: [],
		typeImg: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if(options.id) {
            this.setData({
                id: options.id,
                cid: options.cid
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.init();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    // 初始化
    init() {
        let val = {
            customerId: this.data.cid,
            diagnosisId: this.data.id
        }
        let url = app.$api.addFollows
        if(this.data.id) {
            url = app.$api.addFollows
        } else {
            url = app.$api.addFollow
        }
        app.$http.get(url, val).then(({
            data
        }) => {
            let typeListOpt = this.data.typeListOpt;
            let typeList = this.data.typeList
            if(data.actionRxInfos) {
                data.actionRxInfos.forEach((items, index) => {
                    items.indexInfos.forEach((item, i) => {
                        if(item.indexValue) {
                            let val = item.indexValue.split('+');
                            item.value = val;
                        } else {
                            item.value = '';
                        }
                        if(item.actionIndexRecord) {
                            if(item.actionIndexRecord.actionValue) {
                                var value = item.actionIndexRecord.actionValue.split('+');
                                item.actionIndexRecord.vaule = value
                            } else {
                                item.actionIndexRecord.vaule = ''
                            }
                            if(Array.isArray(typeListOpt[index]) && typeListOpt[index].length > 0) {
                                typeListOpt[index] = typeListOpt[index]
                            } else {
                                typeListOpt[index] = []
                            }
                            if(Array.isArray(typeList[index]) && typeList[index].length > 0) {
                                typeList[index] = typeList[index]
                            } else {
                                typeList[index] = []
                            }
                            let typeValue;
                            if(value.length === 1 && item.indexType !== 'CHECKBOX') {
                                value = value.join('');
                                typeValue = value;
                            } else {
                                typeValue = value
                                let typeVal = [];
                                value.forEach(val => {
                                    let num = item.value.indexOf(val);
                                    typeVal[num] = true
                                })
                                value = typeVal
                            }
                            typeListOpt[index][i] = value
                            typeList[index][i] = typeValue
                        }
                    })
                })
            }
            let listVal = this.data.val;
            listVal.diagnosisId = data.did;
            if(data.dietRx && data.dietRx.actionWeightRecord) {
                data.dietRx.weight = data.dietRx.actionWeightRecord.weight
            }
            this.setData({
                info: data,
                dietRx: data.dietRx,
                dietType: data.dietRx?data.dietRx.dietTypes[data.dietRx.dietTypes.length - 1].id:null,
                actionRxInfos: data.actionRxInfos,
                val: listVal,
                typeListOpt: typeListOpt,
                typeList: typeList,
                id: data.did
            }, () => {
                this.getList();
                if (data.dietRx && data.dietRx.dietImageInfos.length > 0) {
                    data.dietRx.dietImageInfos.forEach(item => {
                        if (item.imageTypeId == this.data.dietType) {
                            this.setData({
                                imageList: item.actionImages
                            })
                        }
                    })
                }
                wx.setNavigationBarTitle({
                    title: `${this.data.info.diagnosisDate} 方案`
                })
            })
        })
    },
    getList() {
        app.$http.get(app.$api.addFollowList, this.data.val).then(({ data }) => {
            let list = this.data.list;
			let typeImgList = this.data.typeImgList;
            data.forEach((item, i) => {
                list.push(item);
            })
            this.setData({
                list: list,
                num: data.length
            }, () => {
                wx.hideLoading();
				this.data.list.forEach((item, i) => {
					typeImgList[i] = []
					if(item.dietRx.dietImageInfos.length > 0) {
						item.dietRx.dietImageInfos.forEach(imgBox => {
							item.dietRx.dietTypes.forEach((diet, index) => {
								if(imgBox.imageTypeId == diet.id) {
									typeImgList[i][index] = imgBox.actionImages;
								} else {
									typeImgList[i][index] = [];
								}
							})
						})
					}
				})
				this.setData({
					typeImgList: typeImgList
				}, () => {
					let typeImg = this.data.typeImg;
					this.data.typeImgList.forEach((imgList, i) => {
						if(imgList.length > 0) {
							typeImg[i] = imgList[imgList.length - 1];
						} else {
							typeImg[i] = [];
						}
					})
					this.setData({
						typeImg: typeImg
					})
				})
            })
        })
    },
    // 双向数据绑定
    updateValue(e) {
        updateValue.apply(this, [e, 'dietRx']);
    },
    // 饮食选择
    radioChange(e) {
        let type = e.detail.value;
        let num = 0
        if (this.data.dietRx.dietImageInfos.length > 0) {
            this.data.dietRx.dietImageInfos.forEach(item => {
                if (item.imageTypeId == type) {
                    num = 1;
                    this.setData({
                        imageList: item.actionImages,
                        dietType: type
                    })
                }
            })
        }
        if(num === 0) {
            this.setData({
                imageList: [],
                dietType: type
            })
        }
    },
    // 上传图片
    upload() {
        app.$http.get(app.$api.qiniuUpload).then(({ data }) => {
            let token = data.token;
            wx.chooseImage({
                count: 1,
                sourceType: ['album', 'camera'],
                success: ({ tempFilePaths }) => {
                    qiniu.upload(tempFilePaths[0], ({ imageURL }) => {
                        let val = {
                            imagePath: imageURL,
                            itid: this.data.dietType
                        }
                        let imageList = this.data.imageList;
                        let imgList = []
                        let index = -1;
                        let num = 0;
                        this.data.dietRx.dietImageInfos.forEach((item, i) => {
                            if(item.imageTypeId == this.data.dietType) {
                                num = 1
                                index = i;
                                imgList = item.actionImages
                            }
                        })
                        imageList.push(val)
                        imgList = imageList;
                        if(num === 0) {
                            index = this.data.dietRx.dietImageInfos.length;
                            let actionImages = 'dietRx.dietImageInfos[' + index + '].actionImages'
                            let imageTypeId = 'dietRx.dietImageInfos[' + index + '].imageTypeId';
                            this.setData({
                                imageList: imageList,
                                [imageTypeId]: this.data.dietType,
                                [actionImages]: imgList
                            })
                        } else {
                            let valName = 'dietRx.dietImageInfos[' + index + '].actionImages'
                            this.setData({
                                imageList: imageList,
                                [valName]: imgList
                            })
                        }
                    }, err => {
                        console.log(err)
                    }, {
                        region: 'ECN',
                        domain: 'https://images.bempty.cn',
                        uptoken: token,
                        uptokenURL: token,
                        uptokenFunc: () => token
                    })
                }
            })
        })
    },
    // 删除图片
    delImg(e) {
        let val = e.currentTarget.dataset;
        let dietImageInfos = this.data.dietRx.dietImageInfos;
        let imageList = this.data.imageList;
        dietImageInfos.forEach((item, i) => {
            if(item.imageTypeId == val.item.itid) {
                imageList.splice(val.index, 1);
                item.actionImages = imageList;
            }
        })
        this.setData({
            imageList: imageList,
            ['dietRx.dietImageInfos']: dietImageInfos
        })
    },
    // 预览上传图片
    previewImage() {
        let list = []
        if(this.data.imageList.length > 0) {
            this.data.imageList.forEach(item => {
                list.push(item.imagePath)
            })
        }
        wx.previewImage({
            urls: list
        })
    },
    // 选择类型
    typeChange(e) {
        let typeList = this.data.typeList;
        let val = e.detail;
        let data = e.currentTarget.dataset;
        if(!typeList[data.itemindex]) {
            typeList[data.itemindex] = []
        }
        typeList[data.itemindex][data.index] = val.value;
        this.setData({
            typeList: typeList
        })
    },
	// 往期方案图片列表
	typeRadioChange(e) {
		let val = parseFloat(e.detail.value);
        let index = e.currentTarget.dataset.index;
        let typeImg = this.data.typeImg;
		let num = 0;
        this.data.list[index].dietRx.dietImageInfos.forEach(item => {
            if(item.imageTypeId == val) {
				num = 1;
                typeImg.splice(index, 1, item.actionImages);
            }
        })
		if(num === 0) {
			typeImg[index] = []
		}
        this.setData({
            typeImg: typeImg
        })
	},
	// 预览
	typePreview(e) {
		let i = e.currentTarget.dataset.index;
		let typeImg = [];
		this.data.typeImg[i].forEach(item => {
			typeImg.push(item.imagePath)
		})
		wx.previewImage({
		    urls: typeImg
		})
	},
    // 保存
	sub() {
		let val = {};
		if(this.data.dietRx.weight) {
			val.actionWeightRecord = {
				weight: this.data.dietRx.weight,
				aid: this.data.info.actionRecordId
            }
            if(this.data.dietRx.actionWeightRecord) {
                val.actionWeightRecord.id = this.data.dietRx.actionWeightRecord.id
            }
        }
        let dietImageInfos = this.data.dietRx.dietImageInfos;
		dietImageInfos.forEach(item => {
            let id = '';
			item.actionImages.forEach(img => {
                img.aid = this.data.info.actionRecordId
            })
        })
        val.dietImageInfos = dietImageInfos
		let header = {
		    'Content-Type': 'application/json'
		}
		app.$http.post(app.$api.save, val, header).then(({ data }) => {
			this.recordSave()
		})
	},
	recordSave() {
        let val = [];
        this.data.typeList.forEach((items, i) => {
            items.forEach((item, index) => {
                let list = {
                    aid: this.data.info.actionRecordId,
                    aiid: this.data.actionRxInfos[i].indexInfos[index].id
                }
                if(this.data.actionRxInfos[i].indexInfos[index].actionIndexRecord) {
                    list.id = this.data.actionRxInfos[i].indexInfos[index].actionIndexRecord.id
                }
                if(Array.isArray(item)) {
                    item = item.join('+');
                }
                list.actionValue = item;
                val.push(list);
            })
        })
        let header = {
		    'Content-Type': 'application/json'
		}
		app.$http.post(app.$api.recordSave, val, header).then(({ msg }) => {
            app.$tap.showToast(msg)
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                })
            }, 1500)
        })
    },
    // 跳转详情
    toDetail() {
        wx.navigateTo({
          url: `./../detail/detail?id=${this.data.id}`,
        })
    },
	
	/**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if(this.data.num < this.data.val.size) {
            app.$tap.showToast('暂无更多数据')
        } else {
            let val = this.data.val;
            val.start++;
            this.setData({
                val: val
            }, () => {
                app.$tap.showLoading('加载中', false)
                this.getList()
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})